/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package introse;

import com.sun.net.ssl.internal.ssl.Debug;
import introse.addTransactionProduct;
import java.awt.Color;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;

public class addTransaction extends javax.swing.JDialog {

    private sourceManager sourceMngr;
    private clientManager clientMngr;
    private transactionManager transMngr;
    private productManager prodMngr;
    private List<addTransactionProduct> purchasedProductList;

    public addTransaction(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        loadClientsBox();
        loadSourcesBox();
        prodMngr = new productManager();
        transMngr = new transactionManager();
        purchasedProductList = new ArrayList<addTransactionProduct>();
    }

    public final void loadClientsBox() {
        clientMngr = new clientManager();
        List<String> clientNames = new ArrayList();

        for (client clnt : clientMngr.getClients(true)) {
            clientNames.add(clnt.getClientName());
        }

        ComboBoxModel clientsBoxModel = new DefaultComboBoxModel(clientNames.toArray());
        clientsBox.setModel(clientsBoxModel);
    }

    public final void loadSourcesBox() {
        sourceMngr = new sourceManager();
        List<String> sourceNames = new ArrayList();

        for (source src : sourceMngr.getSources(true)) {
            sourceNames.add(src.getSourceName());
        }

        ComboBoxModel sourcesBoxModel = new DefaultComboBoxModel(sourceNames.toArray());
        sourcesBox.setModel(sourcesBoxModel);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        submitButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        addProductButton = new javax.swing.JButton();
        productPanelScroll = new javax.swing.JScrollPane();
        productPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        invoiceField = new javax.swing.JTextField();
        clientsBox = new javax.swing.JComboBox();
        addClient = new javax.swing.JButton();
        typeOfReceipt = new javax.swing.JComboBox();
        sourcesBox = new javax.swing.JComboBox();
        remarkField = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Add Transaction");

        submitButton.setText("Submit");
        submitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        addProductButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/introse/images/Inventory Add.png"))); // NOI18N
        addProductButton.setText("Add Product");
        addProductButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addProductButtonActionPerformed(evt);
            }
        });

        productPanelScroll.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        productPanel.setLayout(new java.awt.GridLayout(0, 1));
        productPanelScroll.setViewportView(productPanel);

        jLabel1.setText("Invoice Number:");

        jLabel2.setText("Client:");

        jLabel3.setText("Source:");

        jLabel4.setText("Type of Receipt:");

        invoiceField.setBackground(new java.awt.Color(255, 255, 150));
        invoiceField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                invoiceFieldFocusGained(evt);
            }
        });

        clientsBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Walk-In" }));

        addClient.setIcon(new javax.swing.ImageIcon(getClass().getResource("/introse/images/Client Add.png"))); // NOI18N
        addClient.setText("Add Client");
        addClient.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        addClient.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        addClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addClientActionPerformed(evt);
            }
        });

        typeOfReceipt.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Invoice Number", "OS", "DR" }));
        typeOfReceipt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                typeOfReceiptActionPerformed(evt);
            }
        });

        sourcesBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Main Office" }));

        jLabel5.setText("Remark:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel3)
                                            .addComponent(jLabel4)
                                            .addComponent(jLabel1))
                                        .addGap(21, 21, 21)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(typeOfReceipt, 0, 182, Short.MAX_VALUE)
                                            .addComponent(invoiceField)
                                            .addComponent(sourcesBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel5)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(remarkField)
                                            .addComponent(clientsBox, 0, 182, Short.MAX_VALUE))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(addClient)))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 189, Short.MAX_VALUE)
                        .addComponent(submitButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)
                        .addGap(220, 220, 220))
                    .addComponent(productPanelScroll)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addProductButton)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(sourcesBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(typeOfReceipt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(invoiceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(clientsBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(addClient))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(remarkField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(13, 13, 13)
                .addComponent(addProductButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(productPanelScroll, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(submitButton)
                    .addComponent(cancelButton))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void addProductButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addProductButtonActionPerformed
        purchasedProductList.add(new addTransactionProduct(prodMngr.getProducts(true), this.transMngr));
        purchasedProductList.get(purchasedProductList.size() - 1).parentPanel = productPanel;
        productPanel.add(purchasedProductList.get(purchasedProductList.size() - 1));

//        addTransactionProduct product = new addTransactionProduct(productList);
//        product.parentPanel = productPanel;
//        productPanel.add(product);
        productPanel.validate();
        productPanelScroll.validate();
    }//GEN-LAST:event_addProductButtonActionPerformed

    private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitButtonActionPerformed
        if (invoiceField.getText().isEmpty()) {
            invoiceField.setText("Please input an invoice number");
            invoiceField.setBackground(Color.PINK);
            return;
        }

        if (typeOfReceipt.getSelectedIndex() == 0) {
            int invoiceNumber;
            try {
                invoiceNumber = (Integer.parseInt(invoiceField.getText()));
            } catch (Exception ex) {
                invoiceField.setText("Must be numberic");
                invoiceField.setBackground(Color.PINK);
                return;
            }


            if (transMngr.hasInvoiceNumber(invoiceNumber)) {
                invoiceField.setText("Invoice number already exists");
                invoiceField.setBackground(Color.PINK);
                return;
            }
        }

        Boolean isValid = false;
        for (addTransactionProduct purchasedProd : purchasedProductList) {
            if (purchasedProd.getIsActive()) {
                isValid = true;
            }
        }

        if (!isValid) {
            errorDialogue errorMessage = new errorDialogue(null, true);
            errorMessage.setMessage("No products listed");
            errorMessage.setVisible(true);
            return;
        }

        for (addTransactionProduct purchasedProd : purchasedProductList) {
            if (purchasedProd.getIsActive() && !purchasedProd.stockIsEnough()) {
                errorDialogue errorMessage = new errorDialogue(null, true);
                errorMessage.setMessage("Not enough stock for: " + prodMngr.getProduct(purchasedProd.getProductNumber()).getProductName());
                errorMessage.setVisible(true);
                return;
            }
        }

        List<Integer> productNumbers = new ArrayList();
        for (addTransactionProduct purchasedProd : purchasedProductList) {
            if (purchasedProd.getIsActive()) {
                if (productNumbers.contains(purchasedProd.getProductNumber())) {
                    errorDialogue errorMessage = new errorDialogue(null, true);
                    errorMessage.setMessage("Duplicate products detected");
                    errorMessage.setVisible(true);
                    return;
                } else {
                    productNumbers.add(purchasedProd.getProductNumber());
                }
            }
        }

        float totalPrice = 0;
        for (addTransactionProduct purchasedProd : purchasedProductList) {
            totalPrice += purchasedProd.getTotalPrice();
        }

        confirmDialogue dialogue = new confirmDialogue(null, true);
        dialogue.setMessage("Confirm Transaction for " + Float.toString(totalPrice) + " PHP?");
        dialogue.setVisible(true);

        if (dialogue.getReturnStatus() == 1) {
            transMngr.addTransaction(clientMngr.getClients(true).get(clientsBox.getSelectedIndex()).getClientNumber(), sourceMngr.getSources(true).get(sourcesBox.getSelectedIndex()).getSourceNumber(), invoiceField.getText(), remarkField.getText());
            for (addTransactionProduct purchasedProduct : purchasedProductList) {
                purchasedProduct.addTransactionProduct();
            }

            positiveMessage posMsg = new positiveMessage(null, true);
            posMsg.setMessage("Transaction added successfully");
            posMsg.setVisible(true);
            this.dispose();
        }
    }//GEN-LAST:event_submitButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void addClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addClientActionPerformed
        new addClient(null, true).setVisible(true);
        loadClientsBox();
    }//GEN-LAST:event_addClientActionPerformed

    private void typeOfReceiptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_typeOfReceiptActionPerformed
        invoiceField.setBackground(new Color(255, 255, 150));
        if (typeOfReceipt.getSelectedIndex() == 0) {
            invoiceField.setText("");
            invoiceField.setEditable(true);
        } else if (typeOfReceipt.getSelectedIndex() == 1) {
            invoiceField.setText("OS");
            invoiceField.setEditable(false);
        } else if (typeOfReceipt.getSelectedIndex() == 2) {
            invoiceField.setText("DR");
            invoiceField.setEditable(false);
        }
    }//GEN-LAST:event_typeOfReceiptActionPerformed

    private void invoiceFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_invoiceFieldFocusGained
        if (invoiceField.getBackground().equals(Color.PINK)) {
            invoiceField.setText("");
            invoiceField.setBackground(new Color(255, 255, 150));
        }
    }//GEN-LAST:event_invoiceFieldFocusGained

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(addTransaction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(addTransaction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(addTransaction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(addTransaction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                addTransaction dialog = new addTransaction(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addClient;
    private javax.swing.JButton addProductButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JComboBox clientsBox;
    private javax.swing.JTextField invoiceField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel productPanel;
    private javax.swing.JScrollPane productPanelScroll;
    private javax.swing.JTextField remarkField;
    private javax.swing.JComboBox sourcesBox;
    private javax.swing.JButton submitButton;
    private javax.swing.JComboBox typeOfReceipt;
    // End of variables declaration//GEN-END:variables
}
